#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <string>
#include<string.h>
#include <functional>
using namespace std;

namespace ThreadModule
{
    static uint32_t number = 1;
    class Thread
    {
        using func_t =  function<void()>;
    private:
        void EnableRunning()
        {
            _isRunning = true;
        }

        void EnableDetach()
        {
            cout << "线程被分离了" << endl;
            _isDetach = true;
        }

        static void *Routine(void *args)
        {
            Thread * self = static_cast<Thread*>(args);
            self->EnableRunning();
            if(self->_isDetach)
                self->Detach();
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }
    public:
        Thread(func_t func)
            :_tid(0),
            _isDetach(false),
            _isRunning(false),
            res(nullptr),
            _func(func)
        {
            _name = "thread-" + to_string(number++);
        }

        void Detach()
        {
            if(_isDetach)
                return;
            if(_isRunning)
                pthread_detach(_tid);
            EnableDetach();
        }

        bool Start()
        {
            if(_isRunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if(n != 0)
            {
                cerr << "create thread error: " << strerror(n) << endl;
                return false;
            }
            else
            {
                cout << "create thread success" << endl;
                return true;
            }
        }

        bool Stop()
        {
            if(_isRunning)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                {
                    cerr << "Stop thread error: " << strerror(n)  << endl;
                    return false;
                }
                else
                {
                    _isRunning = false;
                    cout << "Stop" << endl;
                    return true;
                }
            }
            return false;
        }

        bool Join()
        {
            if(_isDetach)
            {
                cout << "线程被分离，不能进行Join" << endl;
                return false;
            }
            int n = pthread_join(_tid, &res);
            if(n != 0)
            {
                cerr << "Join thread error: " << strerror(n)  << endl;
                return false;
            }
            else
            {
                cout << "Join success" << endl;
                return true;
            }
        }

        string Name()
        {
            return _name;
        }

        ~Thread()
        {}
    private:
        pthread_t _tid;
        string _name;
        bool _isDetach;
        bool _isRunning;
        void *res;
        func_t _func;
    };
}